package lagou.work3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;

/**
 * 服务器聊天线程
 */
public class ServerThread extends Thread {
    private List<Socket> list;
    private Socket socket;

    /**
     * 动态传入list
     *
     * @param list
     */
    public ServerThread(List<Socket> list, Socket socket) {
        this.socket = socket;
        this.list = list;
    }


    @Override
    public void run() {
        BufferedReader br = null;
        PrintStream printStream = null;

        try {
            System.out.println(list.size());
            //获取新启动的客户端的socket
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printStream = new PrintStream(socket.getOutputStream());
            while (true) {
                String string = br.readLine();
                InetAddress inetAddress = socket.getInetAddress();
                System.out.println("客户端" + inetAddress + string);
                int z = string.indexOf(":");
                String stringContent = string.substring(z + 1);
                System.out.println(stringContent);
                //将服务器接收到的信息，转发到每个客户端中
                if ("bye".equalsIgnoreCase(stringContent)) {
                    System.out.println("客户端" + inetAddress + "已下线!");
                    System.out.println(list.toString());
                    list.remove(socket);
                    break;
                }
                for (Socket socket : list) {
                    printStream = new PrintStream(socket.getOutputStream());
                    printStream.println("服务器转发" + string);
                    System.out.println("已转发到" + socket);
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != printStream) {
                printStream.close();
            }
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}